<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        effect="dark"
        show-icon
      >
      </el-alert>
      <!-- 选择分类项 -->
      <el-row>
        <el-col :span="2">
          选择商品分类:
        </el-col>
        <el-col :span="10">
          <el-cascader
            v-model="catIds"
            :options="ParentRolesList"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children'
            }"
            @change="ParentRolesChange"
            clearable
          >
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab栏 -->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 -->
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="isDisabled"
                size="small"
                @click="addDialogVisible = true"
                >添加参数</el-button
              >
            </el-col>
          </el-row>
          <!-- 表格 -->
          <el-table
            :data="CategoriesListDo"
            style="width: 100%"
            border
            row-key="attr_id"
          >
            <el-table-column type="expand">
              <template slot-scope="data">
                <el-tag
                  v-for="(item, index) in data.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="tagClose(data.row, index)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="data.row.inputVisible"
                  v-model="data.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(data.row)"
                  @blur="handleInputConfirm(data.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(data.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="id" label="#" type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="data">
                <div class="bt">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="index(data.row)"
                    >修改</el-button
                  >
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="del(data.row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 按钮 -->
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="isDisabled"
                size="small"
                @click="addDialogVisible = true"
                >添加属性</el-button
              >
            </el-col>
          </el-row>
          <!-- 表格 -->
          <el-table :data="categoriesList" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="data">
                <el-tag
                  v-for="(item, index) in data.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="tagClose(data.row, index)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="data.row.inputVisible"
                  v-model="data.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(data.row, 'only')"
                  @blur="handleInputConfirm(data.row, 'only')"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(data.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="id" label="#" type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column prop="mg_state" label="操作">
              <template slot-scope="data">
                <div class="bt">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="index(data.row)"
                    >修改</el-button
                  >
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="del(data.row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加静态/动态属性对话框 -->
    <el-dialog
      :title="TitleName"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeaddDialogVisible"
    >
      <el-form
        :model="paramsForm"
        :rules="Rules"
        ref="addruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="labelName" prop="attr_name">
          <el-input v-model="paramsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOnlyUrl">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改静态/动态属性对话框 -->
    <el-dialog
      :title="'修改' + labelName"
      :visible.sync="editeDialogVisible"
      width="50%"
      @close="closeaddDialogVisible"
    >
      <el-form
        :model="paramsForm"
        :rules="Rules"
        ref="addruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="labelName" prop="attr_name">
          <el-input v-model="paramsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editeOnlyUrl">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ParentRolesList: [], // 下拉框的数据
      catIds: [], // select下拉框选择的数据
      categoriesList: [], // 静态属性数据
      CategoriesListDo: [], // 动态属性数据
      addDialogVisible: false, // 控制添加对话框显示
      editeDialogVisible: false, // 控制修改对话框显示
      activeName: 'many', // tab切换
      paramsForm: {
        // 表单数据
        attr_name: ''
      },
      Rules: {
        attr_name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getParentRolesList()
  },
  methods: {
    ParentRolesChange() {
      // 下拉框值改变
      if (this.catIds.length < 3) {
        this.categoriesList = []
        // this.CategoriesListDo = []
        return false
      }
      this.getCategoriesList()
      // this.getCategoriesListDo()
    },
    async getParentRolesList() {
      // 获取select下拉数据
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.ParentRolesList = res.data
    },
    handleClick() {
      // 切换tab
      this.getCategoriesList()
    },
    async getCategoriesList() {
      // 获取表格参数数据
      const { data: res } = await this.$http.get(
        'categories/' + this.catId + '/attributes',
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [] // 将tag取出的转化为数组，便于之后遍历渲染
        item.inputVisible = false // 在每一个对象身上增加控制显示input输入框的属性，便于之后区别每一个对象的问文本框显示隐藏
        item.inputValue = '' // 每一个对象标签的文本框的数据存储
      })
      if (this.activeName === 'many') {
        // 判断当前是哪个页签并且进项赋值
        this.CategoriesListDo = res.data
      } else {
        this.categoriesList = res.data
      }
    },
    closeaddDialogVisible() {
      this.$refs.addruleForm.resetFields()
      this.paramsForm.attr_name = ''
    },
    async addOnlyUrl() {
      // 点确定发送请求添加
      this.$refs.addruleForm.validate(async boolean => {
        if (!boolean) return this.$message.error('格式错误')
        const { data: res } = await this.$http.post(
          'categories/' + this.catId + '/attributes',
          { attr_name: this.paramsForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message({ message: res.meta.msg, type: 'success' })
        this.addDialogVisible = false
        this.getCategoriesList()
      })
    },
    async index(data) {
      // 显示修改对话框
      this.editeDialogVisible = true
      const { data: res } = await this.$http.get(
        'categories/' + data.cat_id + '/attributes/' + data.attr_id
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.paramsForm = res.data
    },
    async editeOnlyUrl() {
      // 修改属性的确定按钮，发出请求
      const { data: res } = await this.$http.put(
        'categories/' +
          this.paramsForm.cat_id +
          '/attributes/' +
          this.paramsForm.attr_id,
        { attr_name: this.paramsForm.attr_name, attr_sel: this.activeName }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editeDialogVisible = false
      this.getCategoriesList()
    },
    async del(data) {
      // 删除属性一步到位哈哈哈
      const datas = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
      ).catch(res => res) // 通过catch捕获错误并且返回res
      if (datas === 'cancel') return
      const { data: res } = await this.$http.delete(
        'categories/' + data.cat_id + '/attributes/' + data.attr_id
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message({ message: res.meta.msg, type: 'success' })
      this.getCategoriesList()
    },
    handleInputConfirm(data) {
      // 控制标签变div
      if (data.inputValue.trim().length === 0) {
        // 判断是否填写了
        data.inputVisible = false
        data.inputValue = ''
        return false
      } else {
        const tag =
          data.attr_vals.length === 0
            ? data.attr_vals.join(',') + data.inputValue
            : data.attr_vals.join(',') + ',' + data.inputValue // 进行tag的字符串拼接
        console.log(tag)
        this.saveTag(data, tag)
        data.inputVisible = false
      }
    },
    showInput(data) {
      // 展示标签变Input框
      data.inputVisible = true
      this.$nextTick(_ => {
        // 页面重新渲染之后才会触发指定的函数
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async saveTag(data, tag) {
      const { data: res } = await this.$http.put(
        'categories/' + data.cat_id + '/attributes/' + data.attr_id,
        { attr_name: data.attr_name, attr_sel: this.activeName, attr_vals: tag }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message({ message: res.meta.msg, type: 'success' })
      this.getCategoriesList()
    },
    tagClose(data, index) {
      data.attr_vals.splice(index, 1)
      var tag = data.attr_vals.join(',') + data.inputValue + ',' // 进行tag的字符串拼接
      tag = tag.slice(0, tag.length - 1)
      this.saveTag(data, tag)
    }
  },
  computed: {
    // 计算属性
    isDisabled() {
      // 是否展示按钮
      if (this.catIds.length === 3) return false
      return true
    },
    catId() {
      // 获取下拉框中的最后一个三级
      if (this.catIds.length === 3) {
        return this.catIds[this.catIds.length - 1]
      }
      return null
    },
    TitleName() {
      if (this.activeName === 'many') {
        return '添加动态参数'
      } else {
        return '添加静态属性'
      }
    },
    labelName() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-cascader {
  margin-top: -5px;
  margin-left: 5px;
}
.el-tabs {
  margin-top: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
